import {
	getWechatToken,
	getForumsList,
	getPhone,
	getCheckExists,
	postAddRegister
} from "@/utils/api";


// 获取 openId 
function getWechatTokenApi(postData, loginRes, phoneInfo, msg) {
	getWechatToken(postData).then(res => {
		if (res.code === 200) {
			const _userInfo = res.data.user;
			// _userInfo.avatarUrl = msg.userInfo.avatarUrl;
			const openId = res.data.open_id;
			// 判断 User 是否为空，空转为注册，非空直接登录
			if (res.data.user.id) {
				uni.setStorageSync(
					'_token',
					res.data.token.token
				);

				uni.setStorageSync(
					'_userInfo',
					_userInfo
				);

				uni.navigateBack();
			} else {
				// 判断是否成功获取手机号信息
				if (phoneInfo.encryptedData) {
					const phoneData = {
						code: loginRes.code,
						encryptedData: phoneInfo.encryptedData,
						iv: phoneInfo.iv
					};
					handleGetPhone(phoneData, loginRes, phoneInfo, msg, openId);
				} else {
					// 去注册
					handleRegister(msg, openId);
				}

			}
		}
	})
};

// 获取手机号
function handleGetPhone(phoneData, loginRes, phoneInfo, msg, openId) {
	// 获取手机号
	getPhone(phoneData).then(res => {
		if (res.code === 200) {
			let postData = {
				code: loginRes.code
			};
			msg.userInfo.phoneData = res.data.data.phoneNumber; // 获取手机号
			getCheckExistsApi(postData, loginRes, phoneInfo, msg, openId);
		}
	})
};

// 检测是否登陆ID（手机号）是否存在
function getCheckExistsApi(postData, loginRes, phoneInfo, msg, openId) {
	getCheckExists(postData.code).then((req) => {
		if (req.code === 200 && req.data.if_exists === 0) {
			// 去注册
			handleRegister(msg, openId);
		}
	})
};

// 去注册
function handleRegister(msg, openId) {
	uni.showModal({
		title: '提示',
		content: '您还未注册, 是否前往注册',
		success: function (type) {
			if (type.confirm) {
				// 去注册
				const registerDataStr = {
					avatar: msg.userInfo.avatarUrl,
					loginId: msg.userInfo.phoneData,
					openId
				};

				uni.navigateTo({
					url: `/pages/register/register?registerDataStr=${JSON.stringify(registerDataStr)}`
				});
			}
		}
	});
}

// 登录
function handleLogin(phoneInfo) {
	uni.login({
		success: (loginRes) => {
			console.log("loginRes ----->>>", loginRes)
			uni.getUserInfo({
				desc: '授权并获取用户基本信息。',
				success: (msg) => {
					console.log("用户基本信息 ---->>>", msg)
					const postData = {
						code: loginRes.code
					};
					// 获取 openId 
					getWechatTokenApi(postData, loginRes, phoneInfo, msg)
				}
			})
		},
		fail: (info) => {
			console.log("info ------->>>", info)
		}
	})
}

export default handleLogin